#include <func.h>

void cleanup(void* arg) {
	printf("Executing cleanup %s\n", (char*)arg);
}

void* start_routine(void* arg) {
	// 1. 注册线程清理函数
	pthread_cleanup_push(cleanup, (void*)"1");
	pthread_cleanup_push(cleanup, (void*)"2");
	pthread_cleanup_push(cleanup, (void*)"3");

	// 2. 新线程的逻辑
	printf("new thread: Begin\n");
	pthread_cleanup_pop(1);
	sleep(3);
	printf("new thread: End\n");

	// 3. 退出
	// return NULL;
	pthread_exit((void*)9527);

	// 不可能被执行
	// pthread_cleanup_pop(0);
	pthread_cleanup_pop(1);
	pthread_cleanup_pop(1);
}

int main(int argc, char* argv[])
{
	int err;
	pthread_t tid;
	err = pthread_create(&tid, NULL, start_routine, NULL);
	if (err) {
		error(1, err, "pthread_create");
	}
	
	sleep(1);
	// 发送取消请求
	/* err = pthread_cancel(tid); */
	/* if(err) { */
	/* 	error(1, err, "pthread_cancel"); */
	/* } */

	// 等待tid线程结束
	err = pthread_join(tid, NULL);
	if (err) {
		error(1, err, "pthread_join");
	}
    return 0;
}

